<template>
    <div class="gameA">
        <audio @ended="black = false"
            src="https://ziyuan.windbless.top/sounds/lakk/%E8%AE%A9%E6%88%91%E4%BB%AC%E5%AF%B9%E5%9B%BE%E7%89%87%E8%BF%9B%E8%A1%8C%E6%8F%8F%E8%BF%B0%EF%BC%8C%E8%AE%A9%E5%AF%B9%E6%96%B9%E7%8C%9C%E7%8C%9C%E6%98%AF%E5%93%AA%E5%BC%A0%E5%9B%BE%E7%89%87%E3%80%82.mp3"
            ref="audioref"></audio>
        <div class="x" v-if="black" @click="playaudio"></div>
        <div class="main" v-if="topics.length > 0" @click="init">
            <div class="A2img" v-if="nowtopic == 1"> 别人的进度：
                <img class="A2img" :src="`${B2base64}`" alt="">
            </div>

            <game1A v-if="nowtopic == 0" :imgSrc="topics[nowtopic].correctanswer"></game1A>
            <game2A class="A2" v-if="nowtopic == 1" :imgSrc="topics[nowtopic].options.split(',')[1]"></game2A>
            <game3A @next="next3" v-if="nowtopic == 2" :blocknum="topics[nowtopic].options.split(',').length"
                :img="topics[nowtopic].rewardrules"
                :imgSrcArray="topics[nowtopic].options.split(',').slice(0, topics[nowtopic].options.split(',').length / 2)"
                :correctanswer="topics[nowtopic].correctanswer.split(',')"></game3A>
            <reward v-if="nowtopic == 3" :jinbinum="jinbinum"></reward>
        </div>
    </div>
    <!-- <iframe class="iframe" src="https://cloud.windbless.top/#/multiple?channelName=4" frameborder="0"></iframe> -->

</template>
<script setup>
import api from '@/api/user.js'
import game1A from "@/components/gameA/game1A.vue";
import game2A from "@/components/gameA/game2A.vue";
import game3A from "@/components/gameA/game3A.vue";
import reward from "@/components/reward.vue";
import rtcService from '@/until/nimService.js';
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { useAuthStore } from '@/store/index.ts'
import { useRouter } from 'vue-router';
const audiosrc = ref(['https://ziyuan.windbless.top/sounds/lakk/%E5%A4%B8%E8%B5%9E/%E4%BC%98%E7%A7%80%E7%9A%84%E5%B0%8F%E6%9C%8B%E5%8F%8B%E3%80%82.mp3', 'https://ziyuan.windbless.top/sounds/lakk/%E5%A4%B8%E8%B5%9E/%E4%BD%A0%E7%9C%9F%E6%98%AF%E5%8E%89%E5%AE%B3%E7%9A%84%E5%B0%8F%E6%9C%8B%E5%8F%8B%E3%80%82.mp3', 'https://ziyuan.windbless.top/sounds/lakk/%E5%A4%B8%E8%B5%9E/%E4%BD%A0%E7%9C%9F%E6%98%AF%E5%A4%AA%E8%81%AA%E6%98%8E%E4%BA%86%E3%80%82.mp3', 'https://ziyuan.windbless.top/sounds/lakk/%E5%A4%B8%E8%B5%9E/%E5%85%A8%E5%AF%B9%EF%BC%8C%E4%BD%A0%E5%A4%AA%E5%8E%89%E5%AE%B3%E4%BA%86%E3%80%82.mp3', 'https://ziyuan.windbless.top/sounds/lakk/%E5%A4%B8%E8%B5%9E/%E5%B0%8F%E6%9C%8B%E5%8F%8B%E4%BD%A0%E5%A4%AA%E6%A3%92%E4%BA%86%E3%80%82.mp3', 'https://ziyuan.windbless.top/sounds/lakk/%E5%A4%B8%E8%B5%9E/%E8%B6%85%E7%BA%A7%E5%8E%89%E5%AE%B3%E3%80%82.mp3'])
const jinbinum = ref();
const router = useRouter()
const store = useAuthStore();
const uidx = ref();
const topics = ref([]);
const nowtopic = ref(0);
const img2 = ref();
let appkey = '84ac4020443a1d46fe6a24635ba5a0a2'; // 请输入自己的appkey
let channelName; // '您指定的房间号'
let uid; // '您指定的用户ID'
let client, localStream;
const timer = ref(null);
const b1num = ref(0);
const b2num = ref(0);
const audioref = ref(null);
const black = ref(true);
const B2base64 = ref(null);
const playaudio = () => {
    audioref.value.play();
}
watch(nowtopic, (newValue) => {
    if (newValue != 3) {
        sessionStorage.setItem('nowtopic', newValue)
    }
})
onMounted(async () => {
    nowtopic.value = sessionStorage.getItem('nowtopic');
    await getquestion1()
    timer.value = setInterval(() => {
        startlisten();
    }, 2000);
    // init();
})
watch(nowtopic, (newValue) => {
    switch (newValue) {
        case 1:
            audioref.value.src = "https://ziyuan.windbless.top/sounds/lakk/%E8%AE%A9%E6%88%91%E4%BB%AC%E5%AF%B9%E5%9B%BE%E7%89%87%E7%9A%84%E9%A2%9C%E8%89%B2%E8%BF%9B%E8%A1%8C%E6%8F%8F%E8%BF%B0%EF%BC%8C%E6%8C%87%E5%AF%BC%E5%AF%B9%E6%96%B9%E6%9D%A5%E6%B6%82%E8%89%B2%E5%90%A7%E3%80%82.mp3";
            break;
        case 2:
            audioref.value.src = "https://ziyuan.windbless.top/sounds/lakk/%E8%AE%A9%E6%88%91%E4%BB%AC%E6%A0%B9%E6%8D%AE%E6%8F%90%E7%A4%BA%E5%9B%BE%E7%89%87%E5%92%8C%E5%AF%B9%E6%96%B9%E4%B8%80%E8%B5%B7%E5%90%88%E4%BD%9C%E6%8B%BC%E5%A5%BD%E8%BF%99%E4%B8%AA%E5%9B%BE%E7%89%87%E5%90%A7%E3%80%82.mp3";
            break;

    }
})
const putcion = (data) => {
    try {
        return new Promise((resolve) => {

            api.putcion(data).then((res) => {
                console.log(res);
                putprocess({
                    "id": topics.value[nowtopic.value].id,
                    "useranswer": "成功完成",
                    "userrecordingfile": "如果有录音文件路径请写在此",
                    "rewardobtained": `${data.amountofcoinsobtained}coin`
                })
                resolve(1);
            })
        })
    } catch (error) {

    }

}
const putprocess = (data) => {
    console.log(data);
    api.putUserProgress(data).then((res) => {
        console.log(res);
    })
}
function getRandomNumber(x) {
    return Math.floor(Math.random() * (x + 1));
}

const startlisten = () => {

    api.getroom({
        key: store.roomid
    }).then(async (res) => {
        if (res.data.BBBB != null) {
            B2base64.value = res.data.BBBB;
            console.log(B2base64.value);
        }
        if (res.data.B1 != null) {

            console.log(res.data.B1);
            b1num.value++;
            console.log(res.data);

            if (res.data.B1 == topics.value[nowtopic.value].correctanswer) {
                let reward = {};
                if (b1num.value == 1) {
                    jinbinum.value = 10;
                    reward = {
                        "amountofcoinsobtained": jinbinum.value,
                        "reasonforobtainingcoins": `关卡1,${b1num.value}次`
                    }
                } else if (b1num.value == 2) {
                    jinbinum.value = 8;
                    reward = {
                        "amountofcoinsobtained": jinbinum.value,
                        "reasonforobtainingcoins": `关卡1,${b1num.value}次`
                    }
                } else if (b1num.value == 3) {
                    jinbinum.value = 6;
                    reward = {
                        "amountofcoinsobtained": jinbinum.value,
                        "reasonforobtainingcoins": `关卡1,${b1num.value}次`
                    }
                } else {
                    jinbinum.value = 4;
                    reward = {
                        "amountofcoinsobtained": jinbinum.value,
                        "reasonforobtainingcoins": `关卡1,${b1num.value}次`
                    }
                }
                await putcion(reward);
                nowtopic.value = 3;
                audioref.value.src = audiosrc.value[getRandomNumber(audiosrc.value.length - 1)];
                audioref.value.play();
                setTimeout(() => {
                    black.value = true;
                    audioref.value.src = "https://ziyuan.windbless.top/sounds/lakk/%E8%AE%A9%E6%88%91%E4%BB%AC%E5%AF%B9%E5%9B%BE%E7%89%87%E7%9A%84%E9%A2%9C%E8%89%B2%E8%BF%9B%E8%A1%8C%E6%8F%8F%E8%BF%B0%EF%BC%8C%E6%8C%87%E5%AF%BC%E5%AF%B9%E6%96%B9%E6%9D%A5%E6%B6%82%E8%89%B2%E5%90%A7%E3%80%82.mp3";
                    nowtopic.value = 1;
                }, 2000);
            }
        } else if (res.data.B2 != null) {
            console.log(res.data.B2);
            if (res.data.B2 == "ok") {
                b2num.value++;
                let reward = {};
                if (b2num.value == 1) {
                    jinbinum.value = 20;
                    reward = {
                        "amountofcoinsobtained": jinbinum.value,
                        "reasonforobtainingcoins": `关卡2,${b2num.value}次`
                    }
                } else if (b2num.value == 2) {
                    jinbinum.value = 16;
                    reward = {
                        "amountofcoinsobtained": jinbinum.value,
                        "reasonforobtainingcoins": `关卡2,${b2num.value}次`
                    }
                } else if (b2num.value == 3) {
                    jinbinum.value = 12;
                    reward = {
                        "amountofcoinsobtained": jinbinum.value,
                        "reasonforobtainingcoins": `关卡2,${x}次`
                    }
                } else {
                    jinbinum.value = 8;
                    reward = {
                        "amountofcoinsobtained": jinbinum.value,
                        "reasonforobtainingcoins": `关卡2,${b2num.value}次`
                    }
                }
                await putcion(reward);
                nowtopic.value = 3;
                audioref.value.src = audiosrc.value[getRandomNumber(audiosrc.value.length - 1)];
                audioref.value.play();
                setTimeout(() => {
                    black.value = true;
                    audioref.value.src = "https://ziyuan.windbless.top/sounds/lakk/%E8%AE%A9%E6%88%91%E4%BB%AC%E6%A0%B9%E6%8D%AE%E6%8F%90%E7%A4%BA%E5%9B%BE%E7%89%87%E5%92%8C%E5%AF%B9%E6%96%B9%E4%B8%80%E8%B5%B7%E5%90%88%E4%BD%9C%E6%8B%BC%E5%A5%BD%E8%BF%99%E4%B8%AA%E5%9B%BE%E7%89%87%E5%90%A7%E3%80%82.mp3";
                    nowtopic.value = 2;
                }, 2000);

            } else {
                b2num.value == res.data.B2;
            }


        }

    })
}
const getquestion1 = async () => {
    let res = await api.getquestion1({
        creationtime: getCurrentFormattedDate()
    })
    const allTopics = [];
    console.log(res);
    for (const item of res.rows) {
        try {
            const resitem = await api.getonelist({
                questionnumber: item.questionnumber
            });
            console.log(resitem);
            if (resitem.rows[0].difficultylevel == '简单') {
                resitem.rows[0].blocknum = 4;
            } else if (resitem.rows[0].difficultylevel == '中等') {
                resitem.rows[0].blocknum = 6;
            } else if (resitem.rows[0].difficultylevel == '困难') {
                resitem.rows[0].blocknum = 8;
            }
            resitem.rows[0].id = item.id
            allTopics.push(resitem.rows[0]);
        } catch (error) {
            console.error(`Failed to fetch item with questionnumber ${item.questionnumber}:`, error);
        }
    }

    topics.value = allTopics;

}
function getCurrentFormattedDate() {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');

    return `${year}-${month}-${day}`;
}
onUnmounted(() => {
    clearInterval(timer.value);
});
const next3 = async (x) => {
    api.addroom({
        key: store.roomid,
        "game3num": "ok"
    }).then((res) => {
        console.log(res);
    })
    console.log(x);
    let reward = {};
    if (x == 1) {
        jinbinum.value = 20;
        reward = {
            "amountofcoinsobtained": 20,
            "reasonforobtainingcoins": `关卡3,${x}次`
        }
    } else if (x == 2) {
        jinbinum.value = 16;
        reward = {
            "amountofcoinsobtained": 16,
            "reasonforobtainingcoins": `关卡3,${x}次`
        }
    } else if (x == 3) {
        jinbinum.value = 12;
        reward = {
            "amountofcoinsobtained": 12,
            "reasonforobtainingcoins": `关卡3,${x}次`
        }
    } else {
        jinbinum.value = 8;
        reward = {
            "amountofcoinsobtained": 8,
            "reasonforobtainingcoins": `关卡3,${x}次`
        }
    }
    await putcion(reward);
    nowtopic.value = 3;
    audioref.value.src = audiosrc.value[getRandomNumber(audiosrc.value.length - 1)];
    audioref.value.play();
    setTimeout(() => {
        router.push('/finish')
    }, 2000);
}
</script>
<style lang="scss" scoped>
.x {
    position: fixed;
    height: 100vh;
    width: 100vw;
    top: 0px;
    left: 0px;
    background-color: black;
    z-index: 4;
    opacity: 0.6;
}

.gameA {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-image: url('@/static/processback.jpg');
    background-repeat: no-repeat;
    background-size: 100% 100%;
    background-position: center;
    gap: 2rem;

    .main {

        width: 80%;
        height: 80%;
        display: flex;
        gap: 1rem;

        .A2img {
            z-index: 3;
            height: 20%;
            display: flex;
            flex-direction: column;

            img {
                height: 100%;
            }
        }

        .A2 {
            width: 80%;
            height: 80%;
        }
    }

}

.iframe {
    // height: 0vh;
    // width: 60vw;
    position: fixed;
    bottom: 1rem;
    left: 1rem;
}
</style>